package com.dmcb.trade.business.crawlers.author;

import com.dmcb.common.business.constants.CommonConstant;
import com.dmcb.common.web.conversion.JsonResult;
import com.dmcb.trade.business.constants.CrawlConstant;
import com.dmcb.trade.business.crawlers.article.TouZiSheQuParser;
import com.dmcb.trade.business.entities.Article;
import com.dmcb.trade.business.entities.Author;
import com.dmcb.trade.business.mappers.ArticleCrawlMapper;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * created by 王勇 on 2018/9/28.
 */
@Service
public class TouZiSheQuCrawler extends BaseCrawler{

    Logger logger = LoggerFactory.getLogger(BoWangZhiCrawler.class);

    @Autowired
    private TouZiSheQuParser touZiSheQuParser;
    @Autowired
    private ArticleCrawlMapper articleCrawlMapper;

    @Override
    protected String url() {
        return CrawlConstant.TOUZISHEQU_URL;
    }

    @Override
    protected int tag() {
        return CrawlConstant.TOUZISHEQU_TAG;
    }

    @Override
    protected String avatarSelect() {
        return "div.avatar>img";
    }

    @Override
    protected String channelNameSelect() {
        return "div.username";
    }

    /**
     * 频道名称是否同时是作者名称
     *
     * @return 是、否
     */
    @Override
    protected boolean isAuthorName() {
        return true;
    }

    @Override
    protected String listSelect() {
        return "td.column-a";
    }

    @Override
    protected String titleSelect() {
        return "td.column-a>a";
    }

    @Override
    protected String authorSelect() {
        return "div.username";
    }

    @Override
    protected String authorLink() {
        return null;
    }

    @Override
    protected JsonResult crawl(int authorId, String link, Author author, Document doc, boolean all) {
        // 爬取文章
        int page = 1;
        int totalAll = 0;
        //https://bbs.feidee.com/thread-uid-11951632.html
        String id = link.substring(link.lastIndexOf("-")+1,link.lastIndexOf("."));
        String src = "https://bbs.feidee.com/home.php?mod=space&uid="+id+"&do=thread&view=me&order=dateline&from=space&page=";
        doc = webClientUtil.getDoc(src+page);
        if(doc == null ){
            return error("文章解析有误，请联系客服人员");
        }
        while (page <= CrawlConstant.CRAWL_PAGE_TOTAL) {
            JsonResult result = iterate(authorId, doc);
            if (!result.isSuccess()) {
                return result;
            }
            totalAll += result.getInt();
            if (!all && result.getInt() < 1) {
                break;
            }
            page++;
            doc = Jsoup.parse(webClientUtil.getPage(src+page).asXml());
        }
        return totalAll == 0 ? error(CrawlConstant.MSG_WARN_NO_UPDATE) : success(totalAll);
    }

    /**
     * 迭代解析、保存文章
     *
     * @return 成功保存数量
     */
    protected JsonResult iterate(int authorId, Document doc, String listSelect, String titleSelect) {
        Elements elements = doc.select(listSelect);
        if (elements.size() == 0) {
            return success(0);
        }
        int succ = 0;
        int exist = 0;
        for (Element element : elements) {
            // 获取标题、链接元素
            Element ele = element.select(titleSelect).first();
            if (ele != null) {
                try {
                    // 校验作者、标题是否已存在
                    Article article = articleCrawlMapper.queryByAuthorTitle(authorId, ele.text().trim());
                    if (article != null) {
                        exist++;
                        if (exist >= 6 && succ == 0) {
                            return success(0);
                        }
                        continue;
                    }
                    String href ="https://bbs.feidee.com"+ele.attr("href");
                    JsonResult result = parse(authorId, href);
                    succ += result.isSuccess() ? 1 : 0;
                } catch (Exception e) {
                    logger.error("Parser.parse error,{}", ele, e);
                    return error(CommonConstant.ABNORMAL_MSG);
                }
            }
        }
        return success(succ);
    }


    @Override
    protected JsonResult parse(int authorId, String link) throws Exception {
        return touZiSheQuParser.parse(authorId, link);
    }

    @Override
    protected String getBody(Document doc) {
        return touZiSheQuParser.getBody(doc);
    }
}